扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:Doug Purdy Jeffrey Richter 来源:程序员》杂志 2007年11月8日
关键字: Windows
//represents a stock in an application public class Stock:ObservableImpl { //instance variable for ask price object _askPrice; //property for ask price public object AskPrice { set { _askPrice=value; base.NotifyObservers(_askPrice); }//set }//AskPrice property }//Stock //represents the user interface in the application public class StockDisplay:IObserver { public void Notify(object anObject){ Console.WriteLine("The new ask price is:" + anObject); }//Notify }//StockDisplay public class MainClass{ public static void Main() { //create new display and stock instances StockDisplay stockDisplay=new StockDisplay(); Stock stock=new Stock(); //register the grid stock.Register(stockDisplay); //loop 100 times and modify the ask price for(int looper=0;looper < 100;looper++) { stock.AskPrice=looper; } //unregister the display stock.UnRegister(stockDisplay); }//Main }//MainClass |
public class Stock { //declare a delegate for the event public delegate void AskPriceDelegate(object aPrice); //declare the event using the delegate public event AskPriceDelegate AskPriceChanged; //instance variable for ask price object _askPrice; //property for ask price public object AskPrice { set { //set the instance variable _askPrice=value; //fire the event AskPriceChanged(_askPrice); } }//AskPrice property }//Stock class //represents the user interface in the application public class StockDisplay { public void AskPriceChanged(object aPrice) { Console.Write("The new ask price is:" + aPrice + "\r\n"); } }//StockDispslay class public class MainClass { public static void Main(){ //create new display and stock instances StockDisplay stockDisplay=new StockDisplay(); Stock stock=new Stock(); //create a new delegate instance and bind it //to the observer's askpricechanged method Stock.AskPriceDelegate aDelegate=new Stock.AskPriceDelegate(stockDisplay.AskPriceChanged); //add the delegate to the event stock.AskPriceChanged+=aDelegate; //loop 100 times and modify the ask price for(int looper=0;looper < 100;looper++) { stock.AskPrice=looper; } //remove the delegate from the event stock.AskPriceChanged-=aDelegate; }//Main }//MainClass |
濠电姷顣介埀顒€鍟块埀顒€缍婇幃妯诲緞閹邦剛鐣洪梺闈浥堥弲婊勬叏濠婂牊鍋ㄦい鏍ㄧ〒閹藉啴鏌熼悜鈺傛珚鐎规洘宀稿畷鍫曞煛閸屾粍娈搁梻浣筋嚃閸ㄤ即宕㈤弽顐ュС闁挎稑瀚崰鍡樸亜閵堝懎濮┑鈽嗗亝濠㈡ê螞濡ゅ懏鍋傛繛鍡樻尭鐎氬鏌嶈閸撶喎顕i渚婄矗濞撴埃鍋撻柣娑欐崌閺屾稑鈹戦崨顕呮▊缂備焦顨呴惌鍌炵嵁鎼淬劌鐒垫い鎺戝鐎氬銇勯弽銊ф噥缂佽妫濋弻鐔碱敇瑜嶉悘鑼磼鏉堛劎绠為柡灞芥喘閺佹劙宕熼鐘虫緰闂佽崵濮抽梽宥夊垂閽樺)锝夊礋椤栨稑娈滈梺纭呮硾椤洟鍩€椤掆偓閿曪妇妲愰弮鍫濈闁绘劕寮Δ鍛厸闁割偒鍋勯悘锕傛煕鐎n偆澧紒鍌涘笧閹瑰嫰鎼圭憴鍕靛晥闂備礁鎼€氱兘宕归柆宥呯;鐎广儱顦伴崕宥夋煕閺囥劌澧ù鐘趁湁闁挎繂妫楅埢鏇㈡煃瑜滈崜姘跺蓟閵娧勵偨闁绘劕顕埢鏇㈡倵閿濆倹娅囨い蹇涗憾閺屾洟宕遍鐔奉伓